#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glpk.h>
#include "lib/ourlib.h"

double incumbent;

struct tree{
	double *x;
	double z;
	char folder[128];
	char branching_var_name[128]; //variabile di branching in questo nodo
	int branching_var_num;
	int closed;
	int node_number;
	struct tree* b_up;
	struct tree* b_down;
	
};

typedef struct tree tree;

int is_integer(double*,int);

int get_first_frac(double*,int);

int main(int argc,char *argv[]) {
	int i,n,e,v1,v2;
	double z;
	char* SOLUZIONE_FILE = "soluzione";
	char* VARIABLE_TEMPLATE = "x_%d_%d";
	char* FOLDER_TEMPLATE = "node%d";
	FILE* fp;
	tree* root;
	
	incumbent = 0.0;
	root = malloc(sizeof(tree));
	
	fp = fopen(SOLUZIONE_FILE, "r");
	// TODO controlli fp == null
	fscanf(fp,"%d %d %lf\n",&n,&e,&(root->z)); // prima riga: |V| |E| valore_soluzione
	
	root->x = malloc(sizeof(double)*e);
	
	for(i = 0; i < e; i++){
		fscanf(fp,"%d %d %lf\n",&v1,&v2, &((root->x)[i]) );
	} 
	
	
	if(is_integer(root->x,e)){
		printf("Soluzione intera\n");
		root->closed = 1;
	}else{
		int v1,v2;
		double x;
		
		root->closed = 0;
		root->node_number = 0;
		
		printf("Soluzione frazionaria\n");
		printf("%d è una variabile frazionaria\n",get_first_frac(root->x,e));
		root->branching_var_num = get_first_frac(root->x,e);
		
		rewind(fp);
		
		fscanf(fp,"%d %d %lf\n",&v1,&v2,&x); // prima riga: |V| |E| valore_soluzione
		for(i=0; i < (root->branching_var_num); i++){
			fscanf(fp,"%d %d %lf\n",&v1,&v2,&x); // riga: coda testa valore soluzione
		}
		fscanf(fp,"%d %d %lf\n",&v1,&v2,&x);
				
		sprintf( root->branching_var_name, VARIABLE_TEMPLATE,v1,v2);

		
	}
	
	fclose(fp);
	return 0;
}

int is_integer(double* x,int len){
	int i;
	for(i = 0; i < len; i++){
		if(x[i] != 0.0 && x[i] != 1.0)return 0;
	}
	return 1;
}


int get_first_frac(double* x,int len){
	int i;
	for(i = 0; i < len; i++){
		if(x[i] != 0.0 && x[i] != 1.0)return i;
	}
	return -1;
}
